package com.example.mform.service.impl;

import com.example.mform.entity.Choice;
import com.example.mform.entity.FillForm;
import com.example.mform.entity.Question;
import com.example.mform.repository.FillFormRepository;
import com.example.mform.repository.UserFormRepository;
import com.example.mform.service.FillFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shishuqian
 * date 2020/12/18
 * time 9:49
 **/
@Service
public class FillFormServiceImpl implements FillFormService {

    @Autowired
    private FillFormRepository fillFormRepository;

    @Autowired
    private UserFormRepository userFormRepository;

    @Override
    public List<FillForm> findAll() {
        return fillFormRepository.findAll();
    }

    @Override
    public FillForm findById(Long id) {
        return fillFormRepository.findById(id).get();
    }

    @Override
    public void save(List<FillForm> fillForms) {
        fillFormRepository.saveAll(fillForms);
    }

//    @Override
//    public void update(FillForm fillForm) {
//        fillFormRepository.save(fillForm);
//    }

    @Override
    public void deleteById(Long id) {
        fillFormRepository.deleteById(id);
    }

    //查询某问题的答案
    @Override
    public List<String> queryAnswer(Long question_id) {
        return fillFormRepository.queryAnswer(question_id);
    }

    //统计某表单填写的人数
    @Override
    public int countPeople(Long form_id) {
        return fillFormRepository.countPeople(form_id);
    }

    //统计选项被选次数
    @Override
    public int countChoice(Long answer) {
        return fillFormRepository.countChoice(answer);
    }

    //根据表单id统计其中每个问题中选项被选的次数
    @Override
    public List<Question> countResult(Long form_id) {
        //根据问卷id获取该问卷的所有问题
        List<Question> questions = userFormRepository.findById(form_id).get().getQuestions();

        //遍历问卷中所有的问题
        for(Question question : questions){
            //获取该问题的所有选项
            List<Choice> options = question.getOptions();
            //记录每个问题的选项总数
            double sum = 0;

            //统计该问题所有选项的被选总数
            for(Choice choice : options){
                //设置该选项被选的次数
                int count = fillFormRepository.countChoice(choice.getId());
                sum += count;
            }

            for(Choice choice : options){
                //设置该选项被选的次数
                int count = fillFormRepository.countChoice(choice.getId());
                choice.setCount(count);
                if(sum != 0){
                    choice.setPercent(String.format("%.2f",(count/sum)*100) + "%");
                }else{
                    choice.setPercent("0%");
                }
            }

        }
        return questions;
    }
}
